package org.anyin.gitee.shiro.shiro;

import lombok.extern.slf4j.Slf4j;
import org.anyin.gitee.shiro.base.BusinessCodeEnum;
import org.anyin.gitee.shiro.model.UserInfo;
import org.anyin.gitee.shiro.service.ITokenService;
import org.anyin.gitee.shiro.service.IUserInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

@Slf4j
public class TokenRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private ITokenService tokenService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof ShiroToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("user do authorization: {}", principalCollection);
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("user do authentication: {}", authenticationToken);
        ShiroToken token = (ShiroToken)authenticationToken;
        UserInfo userInfo = tokenService.getUserInfo(token.getCredentials().toString());
        if(userInfo == null){
            throw BusinessCodeEnum.TOKEN_INVALID.getException();
        }
        return new SimpleAuthenticationInfo(userInfo.getUsername(), userInfo.getPassword(), userInfo.getNickName());
    }
}
